package com.kalvan.admin.system.service;

import com.alibaba.fastjson.JSONObject;
import com.kalvan.commons.db.DataSourceConstants;
import com.kalvan.core.exception.BizException;
import com.kalvan.core.mybatis.BaseService;
import com.kalvan.core.utils.Sysdate;
import com.kalvan.web.exception.AdminReturnCode;
import com.kalvan.web.servlet.interceptor.CallInterfaceInterceptor;
import com.kalvan.commons.constant.AuditState;
import com.kalvan.commons.constant.State;
import com.kalvan.commons.db.system.mapper.DemoMapper;
import com.kalvan.commons.db.system.model.Demo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 测试流水表Service实现类
 *
 * @author kalvan
 */
@Slf4j
@Service("demoService")
public class DemoService extends BaseService<Demo> {
    @Resource
    DemoMapper mapper;

    @Override
    public void processParams(Map<String, String> params) {
        // TODO 查询和下载的条件检查
        convertBetweenParams(params, "orderDate", false,true);
        convertBetweenParams(params, "orderAmount", false,false);
        convertBetweenParams(params, "createTime", true,false);
    }

    @Override
    @Transactional(value = DataSourceConstants.SYSTEM_TRANSACTION_MANAGER, rollbackFor = Exception.class)
    public int add(Demo demo) {
        // TODO 填充数据,选择字段进行检查，更新人，更新时间，查重
        Demo demoQuery = new Demo();

        if (mapper.selectCount(demoQuery) > 0) {
            throw new BizException(AdminReturnCode.DATA_REPEAT);
        }
        demo.setAuditApplicant(CallInterfaceInterceptor.getUserName());
        // TODO 新增审核,业务状态不生效,审核状态为待审核
        demo.setState(State.DISABLE.getCode());
        demo.setAuditState(AuditState.ADD.getCode());
        return mapper.insertSelective(demo);
    }

    @Override
    @Transactional(value = DataSourceConstants.SYSTEM_TRANSACTION_MANAGER, rollbackFor = Exception.class)
    public int edit(Demo demo) {
        Demo demoDb = mapper.selectByUk(demo.getId());
        if (demoDb == null) {
            throw new BizException(AdminReturnCode.DATA_NOT_EXISTS);
        }
        // TODO 更新指定字段，更新人
        Demo demoNew = new Demo();
        demoNew.setId(demo.getId());
        demoNew.setAuditApplicant(CallInterfaceInterceptor.getUserName());

        // TODO 更新审核,将修改内容保存到json临时字段
        if (demoDb.getAuditState() != AuditState.PASS.getCode()) {
            throw new BizException(AdminReturnCode.DATA_PROCESSING);
        }
        Demo demoTemp = new Demo();
        demoTemp.setTransType(demo.getTransType());
        demoTemp.setOrderDate(demo.getOrderDate());
        demoTemp.setOrderNote(demo.getOrderNote());
        demoTemp.setOrderAmount(demo.getOrderAmount());
        demoTemp.setOrderFee(demo.getOrderFee());
        demoTemp.setOrderFeeRate(demo.getOrderFeeRate());
        demoTemp.setNotifyUrl(demo.getNotifyUrl());
        demoTemp.setBankAccountNo(demo.getBankAccountNo());
        demoTemp.setBankAccountName(demo.getBankAccountName());
        demoTemp.setMobile(demo.getMobile());
        demoTemp.setCertificateNo(demo.getCertificateNo());
        demoTemp.setState(demo.getState());

        demoNew.setAuditState(AuditState.UPDATE.getCode());
        demoNew.setAuditTemp(JSONObject.toJSONString(demoTemp));
        return mapper.updateByUkSelective(demoNew);
    }

    @Override
    @Transactional(value = DataSourceConstants.SYSTEM_TRANSACTION_MANAGER, rollbackFor = Exception.class)
    public int deleteBatch(Object[] ids) {
        int resultNum = 0;
        for (Object id : ids) {
            // TODO 删除审核
            Demo demoDb = mapper.selectByUk(id);
            if (demoDb.getAuditState() != AuditState.PASS.getCode()) {
                throw new BizException(AdminReturnCode.DATA_PROCESSING);
            }
            Demo demoNew = new Demo();
            demoNew.setId(demoDb.getId());
            demoNew.setAuditApplicant(CallInterfaceInterceptor.getUserName());
            demoNew.setAuditState(AuditState.DELETE.getCode());
            resultNum = resultNum + mapper.updateByUkSelective(demoNew);
        }
        return resultNum;
    }

    @Override
    @Transactional(value = DataSourceConstants.SYSTEM_TRANSACTION_MANAGER, rollbackFor = Exception.class)
    public int auditingBatch(Object[] ids, boolean pass) {
        int resultNum = 0;
        String userCode = CallInterfaceInterceptor.getUserName();
        for (Object id : ids) {
            Demo demoDb = mapper.selectByUk(id);
            if (demoDb.getAuditApplicant().equals(userCode)) {
                throw new BizException(AdminReturnCode.DATA_SELF_AUDIT);
            }
            if (demoDb.getAuditState() == AuditState.PASS.getCode()) {
                continue;
            }
            Demo demoNew = new Demo();
            if (pass) {
                //修改审核
                if (AuditState.UPDATE.getCode() == demoDb.getAuditState()) {
                    String object = demoDb.getAuditTemp();
                    if (StringUtils.isBlank(object)) {
                        throw new BizException(AdminReturnCode.DATA_NOT_EXISTS);
                    }
                    Demo demo = JSONObject.parseObject(object, Demo.class);
                    BeanUtils.copyProperties(demo, demoNew);
                }
                //新增审核通过生效
                if (AuditState.ADD.getCode() == demoDb.getAuditState()) {
                    demoNew.setState(State.ENABLE.getCode());
                }
                //删除审核
                if (AuditState.DELETE.getCode() == demoDb.getAuditState()) {
                    resultNum = resultNum + mapper.deleteByUk(demoDb);
                    continue;
                }
            } else {
                //新增审核不通过删除
                if (AuditState.ADD.getCode() == demoDb.getAuditState()) {
                    resultNum = resultNum + mapper.deleteByUk(demoDb);
                    continue;
                }
            }
            demoNew.setId(demoDb.getId());
            demoNew.setAuditUser(userCode);
            demoNew.setUpdateTime(Sysdate.getDate());
            //清除审核标记
            demoNew.setAuditState(AuditState.PASS.getCode());
            //demoNew.setAuditTemp(null);
            resultNum = resultNum + mapper.updateByUkSelective(demoNew);
        }
        return resultNum;
    }

}
